// ignore_for_file: avoid_print

import 'package:flujs/flujs.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flujs_jsc/jsc.dart' as jsc;
import 'package:flujs_qjs/qjs.dart' as qjs;

void main() async {
  runFetch(JSFRuntime rt) async {
    try {
      var ctx = rt.newContext()..loadExtension();
      ctx.eval('''
async function getPost(id) {
  console.log('getPost', id);
  const response = await fetch(`http://localhost:3000/posts/\${id}`);
  const json = await response.json();
  console.log('getPost -> ', json);
  return json;
}
''');
      // rt.executePendingJob(ctx);
      var getPost = ctx.globalObject.getProperty('getPost');
      assert(getPost.isFunction());
      Future<void> execPost(int id) async {
        final st = Stopwatch()..start();
        try {
          print('\n\n\n---(${ctx.rtName})\n\n\n-----');
          var res = getPost.callAsFunction(arguments: [ctx.makeNumber(id)]);
          // assert(res.isPromise());
          var res1 = await ctx.runPromise(res);
          print('res(${ctx.rtName}): $res1');
        } catch (e) {
          print('[execPost] failed: $e \n\n');
        }
        st.stop();
        print('\n timeelapsed: ${st.elapsed}');
      }

      var p = [];
      for (var i = 0; i < 2; i++) {
        p.add(execPost(i));
      }
      await Future.wait(p.cast());
    } catch (e) {
      print('[test failed!!!]$e\n\n\n');
    }
  }

  test('fetch_jsc', () async {
    var rt = jsc.getJSFRuntime();
    await runFetch(rt);
  });
  test('fetch_qjs', () async {
    var rt = qjs.getJSFRuntime();
    await runFetch(rt);
  });
}
